using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using MvcContrib;
using Wayloop.Blog.Core.Data;
using Wayloop.Blog.Core.Data.Entities;


namespace Wayloop.Blog.Presentation.Controllers.Admin
{
    [Authorize]
    public class PostController : AbstractController
    {
        /// <summary>
        /// Gets or sets the <see cref="IPostRepository"/> instance.
        /// </summary>
        /// <value>The <see cref="IPostRepository"/> instance.</value>
        public IPostRepository PostRepository { get; private set; }


        /// <summary>
        /// Initializes a new instance of the <see cref="PostController"/> class.
        /// </summary>
        /// <param name="postRepository">The <see cref="IPostRepository"/> instance.</param>
        public PostController(IPostRepository postRepository)
        {
            PostRepository = postRepository;
        }


        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index()
        {
            IEnumerable<Post> posts = PostRepository.FindAll();
            ViewData["posts"] = posts;
            return View();
        }


        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Create()
        {
            return View();
        }


        [AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
        public ActionResult Create(Post post)
        {
            if (ModelState.IsValid) {
                post.CreatedOn = post.ModifiedOn = DateTime.UtcNow;
                PostRepository.Save(post);

                if (post.Id > 0) {
                    return this.RedirectToAction(x => x.Edit(post.Id));
                }
            }

            return Create();
        }


        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Edit(int id)
        {
            Post post = PostRepository.Find(id);
            if (post == null) {
                throw new HttpException(404, "No post found that matches the specified ID.");
            }

            ViewData["post"] = post;
            return View();
        }


        [AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
        public ActionResult Edit(int id, FormCollection form)
        {
            Post post = PostRepository.Find(id);
            if (TryUpdateModel(post, "post", form.ToValueProvider())) {
                post.ModifiedOn = DateTime.UtcNow;
                PostRepository.Save(post);

                return this.RedirectToAction(x => x.Edit(id));
            }

            return View();
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id)
        {
            throw new NotImplementedException();
        }
    }
}